package com.nit.lab.service.basic.impl;

import com.nit.lab.dto.basic.SghDTO;
import com.nit.lab.dto.utils.PagingDTO;
import com.nit.lab.dto.utils.TableReqDTO;
import com.nit.lab.dto.utils.TableRspDTO;
import com.nit.lab.entity.basic.SghEntity;
import com.nit.lab.mapper.basic.SghMapper;
import com.nit.lab.service.basic.SghService;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;

@Service
public class SghServiceImpl implements SghService {

    @Autowired(required = false)
    private SghMapper sghMapper;

    @Override
    public TableRspDTO list4Table(TableReqDTO tableReqDTO) throws Exception {
        Long count = sghMapper.count4Table(
                tableReqDTO.parseQueryParam("sghName"),
                tableReqDTO.parseQueryParam("sghTel"));
        PagingDTO pagingDTO = new PagingDTO(
                tableReqDTO.getPageNo(),
                tableReqDTO.getPageSize(),
                count,
                sghMapper.list4Table(
                        tableReqDTO.getStart(),
                        tableReqDTO.getPageSize(),
                        tableReqDTO.parseQueryParam("loginName"),
                        tableReqDTO.parseQueryParam("userName"),
                        tableReqDTO.getSortField(),
                        tableReqDTO.getSortOrder()));
        TableRspDTO tableRspDTO = new TableRspDTO(pagingDTO);
        return tableRspDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer add(SghDTO sghDTO) throws Exception {
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        SghEntity sghEntity = mapperFactory.getMapperFacade().map(sghDTO, SghEntity.class);
        return sghMapper.add(sghEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer update(SghDTO sghDTO) throws Exception {
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        SghEntity sghEntity = mapperFactory.getMapperFacade().map(sghDTO, SghEntity.class);
        return sghMapper.update(sghEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer remove(String sghIds) throws Exception {
        String[] arraySghId = sghIds.split(",");
        for (int i = 0; i < arraySghId.length; i++) {
            sghMapper.remove(Long.parseLong(arraySghId[i]));
        }
        return arraySghId.length;
    }
}
